<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use app\model\EnterpriseMember;
use think\Model;
use think\Request;
use think\response\Json;

class Role extends BaseController
{
    protected Model $model;
    protected int $limit;
    public function initialize(): void
    {
        $this->model  = new \app\model\Role();
        $this->limit = env('ENTERPRISE_ROLE_LIMIT') | 10;
    }
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request): \think\Response
    {
        $data = $request->get();
        try {
            $data = $this->model->whereOr('enterprise_id',$data['enterprise_id'])
                ->whereOr('enterprise_id',0)
                ->withoutField('permissions')
                ->select();
            return $this->result(200,'角色列表',$data);
        }catch (\Exception $e){
            return $this->result($e->getCode(),$e->getMessage());
        }
    }

    /**
     * 显示指定的资源
     * @param Request $request
     * @return Json
     */
    public function detail(Request $request): Json
    {
        $id = $request->get('id');
        try {
            $data = $this->model->where('id',$id)->find()->toArray();
            return $this->result(200,'角色详情',$data);
        }catch (\Exception $e){
            return $this->result($e->getCode(),$e->getMessage());
        }
    }
    public function save(Request $request): Json
    {
        $data = $request->post();
        $data['permissions'] = json_encode($data['permissions']);
        try {
            //检查创建角色数量上限
            $count = $this->model->where('enterprise_id',$data['enterprise_id'])->count();
            if($count >= $this->limit){
                return $this->result(403,'企业角色数量已达上限');
            }
            //角色名称查重
            $role = $this->model->whereOR('role_name',$data['role_name'])
                ->whereOr('ident',$data['ident'])
                ->where('enterprise_id',$data['enterprise_id'])
                ->count();
            if($role){
                return $this->result(403,'角色名称已存在');
            }
            $this->model->create($data);
            return $this->result(200,'角色创建成功');
        }catch (\Exception $e){
            return $this->result($e->getCode(),$e->getMessage());
        }
    }
    public function update(Request $request): Json
    {
        $data = $request->post();
        if (!$data['permissions']['workbench'] && !$data['permissions']['admin']){
            return $this->result(403,'请选择权限');
        }
        $data['permissions'] = json_encode($data['permissions']);
        try {
            $conditions = [
                ['enterprise_id', '=', $data['enterprise_id']],
                ['id', '<>', $data['id']]
            ];

            $orConditions = [
                ['role_name', '=', $data['role_name']],
            ];

            // 构建查询条件，确保逻辑清晰
            $role = $this->model->where($conditions)->whereOr($orConditions)->count();
            if($role){
                return $this->result(403,'角色名称已存在');
            }
            $this->model->update($data,['id'=>$data['id']]);
            return $this->result(200,'角色更新成功');
        }catch (\Exception $e){
            return $this->result($e->getCode(),$e->getMessage());
        }
    }
    public function delete($id): Json
    {
        try {
            //检查该角色下是否存有用户
            $user = (new EnterpriseMember())->where('role_id',$id)->find();
            if ($user){
                return $this->result(403,'该角色下存在用户，无法删除');
            }
            $this->model->where('id',$id)->delete();
            return $this->result(200,'角色删除成功');
        }catch (\Exception $e){
            return $this->result($e->getCode(),$e->getMessage());
        }
    }
}
